<?php

namespace app\admin\controller\individuality;

use addons\shopro\service\Wallet as WalletService;
use app\admin\model\Admin;
use app\common\controller\Backend;
use Exception;
use fast\Random;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;
use think\Validate;

/**
 * 个体户管理
 *
 * @icon fa fa-circle-o
 */
class Individuality extends Backend
{

    /**
     * Individuality模型对象
     * @var \app\admin\model\Individuality
     */
    protected $model = null;
    protected $is_individuality = 0;
    protected $admin = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Individuality;
        $this->view->assign("statusList", $this->model->getStatusList());
        //新增lina start
        $group_ids=$this->auth->getGroupIds();
        if($group_ids[0]==2){
            //个体户
            $this->admin=$this->auth->getUserInfo();
            if(!empty($this->admin["individuality_id"])){
                $this->is_individuality=1;
            }
        }
        //新增lina end
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $this->assign("is_individuality",$this->is_individuality);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $where_indivi=[];
        if($this->is_individuality==1){
            //个体户
            $where_indivi=["id"=>$this->admin["individuality_id"]];
        }
        $list = $this->model
            ->where($where)
            ->where($where_indivi)
            ->order($sort, $order)
            ->paginate($limit);
        $store=$this->model->where(["status"=>2])->select();
        $redis_key = 'individuality|store';
        if(!redis_cache()->exists($redis_key)){
            // 把所有个体户插入列表中
            foreach ($store as $key => $store) {
                redis_cache()->rPush($redis_key, $store['id']);
            }
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $data = [
            ['name', 'require', '请输入名称'],
            ['contacts', 'require', '请输入联系人'],
            ['business_license', 'require', '请上传营业执照'],
            ['address', 'require', '请输入地址'],
            ['account', 'require', '请输入账号'],
            ['password', 'require', '请输入密码'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        $result = false;
        Db::startTrans();
        try {
            if (!Validate::is($params['password'], '\S{6,30}')) {
                exception(__("Please input correct password"));
            }
            $admin_data['salt'] = Random::alnum();
            $admin_data['password'] = $this->auth->getEncryptPassword($params['password'], $admin_data['salt']);
            $admin_data['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
            $admin_data['username'] =$params["account"];
            $admin_data['nickname'] =$params["name"];
            $result = $this->model->allowField(true)->save($params);
            $admin_data["individuality_id"]=$this->model->id;
            $model=new Admin();
            $result = $model->validate('Admin.add')->save($admin_data);
            if ($result === false) {
                exception($model->getError());
            }
            $dataset[] = ['uid' => $model->id, 'group_id' => 2];
            model('AuthGroupAccess')->saveAll($dataset);
            $redis_key = 'individuality|store';
            redis_cache()->rPush($redis_key, $this->model->id);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $data = [
            ['name', 'require', '请输入名称'],
            ['contacts', 'require', '请输入联系人'],
            ['business_license', 'require', '请上传营业执照'],
            ['address', 'require', '请输入地址'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        $result = false;
        Db::startTrans();
        try {
            if ($params['password']) {
                if (!Validate::is($params['password'], '\S{6,30}')) {
                    exception(__("Please input correct password"));
                }
                $admin_data['salt'] = Random::alnum();
                $admin_data['password'] = $this->auth->getEncryptPassword($params['password'], $admin_data['salt']);
            } else {
                unset($params['password'], $params['salt']);
            }
            $redis_key = 'individuality|store';
            if(isset($params['status'])){
                //修改个体户状态
                if($params['status']==2){
                    //接单
                    if($row["status"]!=2){
                        redis_cache()->rPush($redis_key,$ids);
                    }
                }else{
                    //停止接单
                    if($row["status"]!=1){
                        redis_cache()->lRem($redis_key,$ids,0);
                    }
                }
            }
            //$admin_data['username'] =$params["account"];
            $admin_data['nickname'] =$params["name"];
            $result = $row->allowField(true)->save($params);
            $model = Admin::where(["individuality_id"=>$ids])->find();
            $result1 = $model->save($admin_data);
            if ($result1 === false) {
                exception($model->getError());
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        $model=new Admin();
        Db::startTrans();
        try {
            $redis_key = 'individuality|store';
            foreach ($list as $item) {
                $count += $item->delete();
                $admin=$model->where(["individuality_id"=>$item["id"]])->find();
                if(!empty($admin)){
                    model('AuthGroupAccess')->where(["uid"=>$admin->id])->delete();
                    $admin->delete();
                }
                redis_cache()->lRem($redis_key,$item["id"],0);
            }
            $deleteIds=Admin::whereIn("individuality_id",$ids)->column("id")[0];
            if(!empty($deleteIds)){
                Admin::where('uid', 'in', $deleteIds)->delete();
                model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        $redis_key = 'individuality|store';
        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
                if(isset($values['status'])){
                    //修改个体户状态
                    if($values['status']==2){
                        //接单
                        redis_cache()->rPush($redis_key,$item["id"]);
                    }else{
                        //停止接单
                        redis_cache()->lRem($redis_key,$item["id"],0);
                    }
                }
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 提现
     * */
    public function payment()
    {
        $row = $this->model->get($this->admin["individuality_id"]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        if($row["money"]<=0) $this->error("可提现金额不足");
        $params = $this->request->post('row/a');
        if($params["money"]<=0) $this->error("请填写正确提现金额");
        if($params["money"]>$row["money"]) $this->error("可提现金额不足");
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $result = false;
        Db::startTrans();
        try {
            $model= new \app\admin\model\individuality\Withdrawal();
            $result=$model->save([
                "individuality_id"=>$this->admin["individuality_id"],
                "money"=>$params["money"],
            ]);
            WalletService::changeIndividuality($row, -$params["money"], [
                'order_id' => $model->id,
            ],"提现",1);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
